#!/bin/sh

# Installs the system into a zipped floppy image file

BOOTSECTOR=ailes.bss
TMPMOUNTDIR="$M_DIR_TMP/tmp_mnt"
SYSLINUXCFG="$M_DIR_TMP/syslinux.cfg"
SYSLINUXLOG="$M_DIR_TMP/syslinux.log"
DISTCOMMENT="$M_DIR_TMP/distcomment"
ZIPLOG="$M_DIR_TMP/zip.log"

echo ""
echo "Making FLOPPY IMAGE file"

while [ "$1" != "" ] ; do
	# Are we doing a release version?  If the argument is "-r" then we use
	# the release number in the destination directory name.  Otherwise, we
	# assume an interim package and use the date instead
	if [ "$1" == "-r" ] ; then
		# What is the current release version?
		RELEASE=`${M_DIR_UTILS}/release.sh`
		echo " - doing RELEASE version $RELEASE"
	fi

	if [ "$1" == "-isoboot" ] ; then
		# Only doing an ISO boot floppy (just the kernel and OS loader)
		ISOBOOT=-isoboot
		echo " - doing ISO boot image"
	fi

	if [ "$1" == "-syslinux" ] ; then
		# Make it a syslinux image
		SYSLINUX=-syslinux
		echo " - doing SYSLINUX boot image"
	fi

	shift
done

if [ "$RELEASE" == "" ] ; then
	# What is the date?
	RELEASE=`date +%Y-%m-%d`
	echo " - doing INTERIM version $RELEASE (use -r flag for RELEASES)"
fi

NAME=ailes-"$RELEASE"
IMAGEFILE="$NAME""$ISOBOOT".img
ZIPFILE="$NAME""$ISOBOOT"-img.zip
rm -f "$IMAGEFILE"
cp "$M_DIR_UTILS/blankfloppy.gz" "$IMAGEFILE".gz
gunzip "$IMAGEFILE".gz

if [ "$ISOBOOT" != "" ] ; then
	"$M_DIR_UTILS/install.sh" -isoboot "$IMAGEFILE"
else
	"$M_DIR_UTILS/install.sh" -basic "$IMAGEFILE"
fi

if [ $? -ne 0 ] ; then
	exit $?
fi

if [ "$SYSLINUX" != "" ] ; then
	dd if=$IMAGEFILE bs=512 count=1 of=./$BOOTSECTOR >& /dev/null
	syslinux $IMAGEFILE >& "$SYSLINUXLOG"
	if [ $? -ne 0 ] ; then
		echo ""
		echo -n "Not able to make syslinux image.  See $SYSLINUXLOG.  "
		echo "Terminating"
		echo ""
		exit $?
	fi
	mkdir -p "$TMPMOUNTDIR"
	$MOUNT -o loop -t msdos $IMAGEFILE $TMPMOUNTDIR
	echo "default Ailes" > $SYSLINUXCFG
	echo "label Ailes" >> $SYSLINUXCFG
	echo "	kernel $BOOTSECTOR" >> $SYSLINUXCFG
	cp ./$BOOTSECTOR $SYSLINUXCFG $TMPMOUNTDIR
	$UMOUNT "$TMPMOUNTDIR"
	rm -f ./$BOOTSECTOR $SYSLINUXCFG $SYSLINUXLOG
	if [ -d "$TMPMOUNTDIR" ] ; then
		rmdir "$TMPMOUNTDIR"
	fi
fi

echo -n "Archiving... "
echo "Ailes $RELEASE Image Release" > "$DISTCOMMENT"
echo "Copyright (C) 1998-2007 J. Andrew McLaughlin" >> "$DISTCOMMENT"
echo "Copyright (C) 2009 Vadim Ushakov" >> "$DISTCOMMENT"
rm -f "$ZIPFILE"
zip -9 -z -r "$ZIPFILE" "$IMAGEFILE" < "$DISTCOMMENT" >& "$ZIPLOG"
if [ $? -ne 0 ] ; then
	echo ""
	echo -n "Not able to create zip file $ZIPFILE.  "
	echo "See $ZIPLOG.  Terminating."
	echo ""
	exit 1
fi
rm -f "$DISTCOMMENT" "$ZIPLOG"
echo Done

echo ""
echo "File is: $ZIPFILE"
echo ""

exit 0
